package com.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fire.exception.ServiceException;
import com.fire.mapper.MachineMapper;
import com.fire.model.entity.Machine;
import com.fire.model.entity.Monitor;
import com.fire.model.entity.Smart;
import com.fire.mapper.SmartMapper;
import com.fire.model.enums.SmartEnum;
import com.fire.response.ResponseCodeEnum;
import com.fire.service.ISmartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 智能导航表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-04-07
 */
@Service
@RequiredArgsConstructor
public class SmartServiceImpl extends ServiceImpl<SmartMapper, Smart> implements ISmartService {

    private final MachineMapper machineMapper;

    @Override
    public Map<String, Object> querySmartData(Integer pageNo, Integer pageSize, String location) {
        Page<Smart> pageInfo = new Page<>(pageNo, pageSize);
        String locationTrim = "";
        if(!StringUtils.isBlank(location)){
            locationTrim = location.trim();
        }
        QueryWrapper<Smart> wrapper = new QueryWrapper<>();
        wrapper.like("location_name", locationTrim);
        wrapper.orderByDesc("create_time");
        Page<Smart> smartPage = baseMapper.selectPage(pageInfo, wrapper);
        if(null != smartPage){
            Map<String,Object> map = new HashMap<>();
            map.put("data", smartPage.getRecords());
            map.put("total", smartPage.getTotal());
            return map;
        }
        return null;
    }

    @Override
    public List<String> queryMachineId(Integer id) {
        Smart smart = baseMapper.selectById(id);
        QueryWrapper<Machine> wrapper = new QueryWrapper<>();
        wrapper.eq("location", smart.getLocationName());
        List<String> machineIds = machineMapper.selectList(wrapper).stream().map(Machine::getMachineId).collect(Collectors.toList());
        return machineIds;
    }

    @Override
    public void handlerSent(Integer id, String machineId) throws ServiceException {
        Smart smart = baseMapper.selectById(id);
        if(null == smart) {
            throw new ServiceException(ResponseCodeEnum.SENT_ERROR);
        }
        QueryWrapper<Machine> wrapper = new QueryWrapper<>();
        wrapper.eq("machine_id", machineId);
        Machine machine = machineMapper.selectOne(wrapper);
        if(null == machine) {
            throw new ServiceException(ResponseCodeEnum.SENT_ERROR);
        }
        smart.setStatus(SmartEnum.SENT);
        baseMapper.updateById(smart);

        machine.setWaitTask(machine.getWaitTask() + 1);
        machineMapper.updateById(machine);
    }
}
